package jsu.blogger.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.mail.*;
import javax.mail.internet.*;

import java.util.Properties;

@Component
public class EmailUtil {

    private static final Logger log = LoggerFactory.getLogger(EmailUtil.class);
    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.username}")
    private String user;

    @Value("${spring.mail.password}")
    private String password;
    private int timeout = 5000; // 读取超时，单位为毫秒
    private int connectionTimeout = 5000; // 连接超时，单位为毫秒
    //to目标邮箱 subject标题 body内容
    public void sendEmail(String to, String subject, String body) {
        //System.out.println(host);
        // 设置邮件服务器的属性
        Properties properties = new Properties();
        properties.setProperty("mail.smtp.host", host);
        properties.setProperty("mail.smtp.port", "465");
        properties.setProperty("mail.smtp.auth", "true");
        properties.setProperty("mail.smtp.starttls.enable", "true"); // 对于587端口
        properties.setProperty("mail.smtp.ssl.enable", "true"); // 对于465端口

        // 获取默认的邮件会话
        Session session = Session.getInstance(properties, new Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(user, password);
            }
        });

        try {
            // 创建默认的 MimeMessage 对象
            MimeMessage message = new MimeMessage(session);

            // 设置 From: 头部字段
            message.setFrom(new InternetAddress(user));

            // 设置 To: 头部字段
            message.addRecipient(Message.RecipientType.TO, new InternetAddress(to));

            // 设置 Subject: 头部字段
            message.setSubject(subject);

            // 设置消息体
            message.setText(body);

            // 发送消息
            Transport.send(message);
            log.info("成功发送邮件给：" + to);
        } catch (MessagingException mex) {
            mex.printStackTrace();
        }
    }
}
